import sys
import cv2
import time
import numpy as np
from PyQt5.QtGui import QFont, QPainter, QBrush, QColor, QPen, QPixmap, QImage
from PyQt5.QtCore import QTimer, Qt, QRect
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QVBoxLayout, QHBoxLayout, QPushButton, QGridLayout

# 固定的颜色阈值
BLACK_THRESHOLD = 135  # 黑棋
WHITE_THRESHOLD = 150  # 白棋


class VideoWindow(QWidget):
    def __init__(self, parent=None):
        super(VideoWindow, self).__init__(parent)

        self.video_size = (640, 480)
        self.image_size = (640, 480)
        self.image_label = QLabel()
        self.video_label = QLabel()
        self.top_left = (0, 0)
        self.top_right = (0, 0)
        self.bottom_left = (0, 0)
        self.bottom_right = (0, 0)
        self.weizhi = [(36, 36), (170, 30), (303, 36),
                       (36, 170), (170, 170), (303, 170),
                       (36, 303), (170, 303), (303, 303)]

        self.jiugongge = [0] * 9
        self.state = [0] * 9
        self.zhixing = 1
        self.move = 0
        self.winner = -1
        self.no_1 = 1
        self.people_move = 0
        self.system_move = 0
        self.cheat_flag = 0
        self.text_label = QLabel("系统执黑棋")
        self.text_label.setFont(QFont(self.text_label.font().family(), 28))
        self.text_label.setAlignment(Qt.AlignHCenter)
        self.text_label_dowm_state = QLabel("等待下棋")
        self.text_label_dowm_state.setFont(QFont(self.text_label_dowm_state.font().family(), 25))
        self.text_label_dowm_state.setAlignment(Qt.AlignHCenter)
        self.text_label_cheat_state = QLabel("无作弊")
        self.text_label_cheat_state.setFont(QFont(self.text_label_cheat_state.font().family(), 25))
        self.text_label_cheat_state.setAlignment(Qt.AlignHCenter)
        self.text_label_5 = QLabel("当前剩余_颗黑棋 _颗白棋")
        self.text_label_5.setFont(QFont(self.text_label_5.font().family(), 20))
        self.text_label_5.setAlignment(Qt.AlignHCenter)

        self.switch_button = QPushButton("切换执棋手")
        self.switch_button.clicked.connect(self.switch_button_clicked)
        self.switch_button_1 = QPushButton("棋手已下完")
        self.switch_button_1.clicked.connect(self.switch_button_1_clicked)
        self.square_button_simulation = QPushButton("系统已落子")
        self.square_button_simulation.clicked.connect(self.square_button_simulation_clicked)

        self.square_button_0 = QPushButton("空")
        self.square_button_1 = QPushButton("空")
        self.square_button_2 = QPushButton("空")
        self.square_button_3 = QPushButton("空")
        self.square_button_4 = QPushButton("空")
        self.square_button_5 = QPushButton("空")
        self.square_button_6 = QPushButton("空")
        self.square_button_7 = QPushButton("空")
        self.square_button_8 = QPushButton("空")
        self.square_button_0.clicked.connect(self.square_button_0_clicked)
        self.square_button_1.clicked.connect(self.square_button_1_clicked)
        self.square_button_2.clicked.connect(self.square_button_2_clicked)
        self.square_button_3.clicked.connect(self.square_button_3_clicked)
        self.square_button_4.clicked.connect(self.square_button_4_clicked)
        self.square_button_5.clicked.connect(self.square_button_5_clicked)
        self.square_button_6.clicked.connect(self.square_button_6_clicked)
        self.square_button_7.clicked.connect(self.square_button_7_clicked)
        self.square_button_8.clicked.connect(self.square_button_8_clicked)

        self.text_label_1 = QLabel("胜利者：暂无")
        self.text_label_1.setFont(QFont(self.text_label_1.font().family(), 30))
        self.text_label_1.setAlignment(Qt.AlignHCenter)
        self.text_label_2 = QLabel("系统决定下第_位")
        self.text_label_2.setFont(QFont(self.text_label_2.font().family(), 32))
        self.text_label_2.setAlignment(Qt.AlignHCenter)
        self.text_label_3 = QLabel(" ")
        self.text_label_3.setFont(QFont(self.text_label_3.font().family(), 34))
        self.text_label_3.setAlignment(Qt.AlignHCenter)

        self.VD_Box = QVBoxLayout()
        self.VD_Box.addWidget(self.video_label)
        self.image_11_label = QLabel()
        self.VD_Box.addWidget(self.image_11_label)
        self.video_label.setGeometry(50, 50, 640, 480)
        self.video_label.setAlignment(Qt.AlignTop | Qt.AlignHCenter)

        self.image_label.setGeometry(50, 600, 400, 400)
        pixmap_jiuge = QPixmap('/home/sunrise/YOLOv10/try/YOLOv10/ImageTransfer/jiuge.jpg')
        self.image_label.setPixmap(pixmap_jiuge.scaled(400, 400, Qt.KeepAspectRatio))

        self.switchBox = QHBoxLayout()
        self.switchBox.addWidget(self.switch_button)
        self.switchBox.addWidget(self.switch_button_1)
        self.Button_chess_0 = QHBoxLayout()
        self.Button_chess_0.addWidget(self.square_button_0)
        self.Button_chess_0.addWidget(self.square_button_1)
        self.Button_chess_0.addWidget(self.square_button_2)
        self.Button_chess_1 = QHBoxLayout()
        self.Button_chess_1.addWidget(self.square_button_3)
        self.Button_chess_1.addWidget(self.square_button_4)
        self.Button_chess_1.addWidget(self.square_button_5)
        self.Button_chess_2 = QHBoxLayout()
        self.Button_chess_2.addWidget(self.square_button_6)
        self.Button_chess_2.addWidget(self.square_button_7)
        self.Button_chess_2.addWidget(self.square_button_8)
        self.Button_chess_jin = QVBoxLayout()
        self.Button_chess_jin.addWidget(self.text_label_5)
        self.Button_chess_jin.addWidget(self.square_button_simulation)
        self.Button_chess_jin.addLayout(self.Button_chess_0)
        self.Button_chess_jin.addLayout(self.Button_chess_1)
        self.Button_chess_jin.addLayout(self.Button_chess_2)
        self.chess_Box = QHBoxLayout()
        self.chess_Box.addWidget(self.image_label)
        self.chess_Box.addLayout(self.Button_chess_jin)
        self.ButtonBox = QVBoxLayout()
        self.ButtonBox.addLayout(self.chess_Box)
        self.ButtonBox.addLayout(self.switchBox)
        self.ButtonBox.addWidget(self.text_label)
        self.wait_and_cheat = QHBoxLayout()
        self.wait_and_cheat.addWidget(self.text_label_dowm_state)
        self.wait_and_cheat.addWidget(self.text_label_cheat_state)
        self.ButtonBox.addLayout(self.wait_and_cheat)
        self.ButtonBox.addWidget(self.text_label_1)
        self.ButtonBox.addWidget(self.text_label_2)
        self.ButtonBox.addWidget(self.text_label_3)
        self.layout = QHBoxLayout()
        self.layout.addLayout(self.VD_Box)
        self.layout.addLayout(self.ButtonBox)
        self.setLayout(self.layout)
        self.setGeometry(100, 100, 1000, 1000)
        self.setWindowTitle('三子棋')

        self.capture = cv2.VideoCapture(1)
        self.capture.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
        self.capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
        if not self.capture.isOpened():
            exit(-1)

        self.white_lower = np.array([127, 127, 127])  # 黑棋 BGR
        self.white_upper = np.array([255, 255, 255])  # 白棋 BGR
        self.black_lower = np.array([0, 0, 0])  # 黑棋 BGR
        self.black_upper = np.array([126, 126, 126])  # 白棋 BGR

        self.white_pieces = []
        self.black_pieces = []
        self.squares_center = []
        self.square_points = []
        self.find_rect = 0
        self.lower_black_hsv = np.array([0, 0, 150])
        self.upper_black_hsv = np.array([180, 255, 256])
        self.xiao_xiebian_half = 0
        self.bianchang_half = 0
        self.square_size = 0
        self.neijie_radius = 0
        self.center_big_square = np.array([0, 0])
        self.angle = 0
        self.jiaodu = 0
        self.radius_tolerance = 10
        self.radius_average = 0
        self.aver_door = 0
        self.radius_sum = 0
        self.circle_count = 0
        self.white_window = [0] * 10
        self.black_window = [0] * 10
        self.consecutive_no_piece_counts = [0] * 9

        self.timer = QTimer()
        self.timer.timeout.connect(self.update_frame)
        self.timer.start(int(1000 / 60))

    def is_point_inside_rotated_rectangle(self, point, rect_center, rect_angle, rect_width, rect_height):
        rotation_matrix = np.array([[np.cos(rect_angle), -np.sin(rect_angle)],
                                    [np.sin(rect_angle), np.cos(rect_angle)]])
        inv_rotation_matrix = np.linalg.inv(rotation_matrix)
        rect_points = np.array([
            [-rect_width / 2, -rect_height / 2],
            [rect_width / 2, -rect_height / 2],
            [rect_width / 2, rect_height / 2],
            [-rect_width / 2, rect_height / 2]
        ])
        rect_points = np.dot(rect_points, rotation_matrix.T) + rect_center
        distances = []
        for i in range(4):
            next_point = rect_points[(i + 1) % 4]
            side_vector = next_point - rect_points[i]
            point_vector = point - rect_points[i]
            side_length = np.linalg.norm(side_vector)
            cross_product = abs(np.cross(side_vector, point_vector)) / side_length
            distances.append(cross_product)
        return all(distance < 0.5 for distance in distances)

    def update_frame(self):
        ret, frame = self.capture.read()
        if ret:
            if self.people_move == 1 and self.system_move == 0 and self.winner == -1:
                self.text_label_dowm_state.setText("等待系统落子...")
            elif self.people_move == 0 and self.system_move == 1 and self.winner == -1:
                self.text_label_dowm_state.setText("等待对手落子...")
            else:
                self.text_label_dowm_state.setText("当前游戏结束")

            blurred = cv2.GaussianBlur(frame, (5, 5), 0)
            kernel = np.ones((5, 5), np.uint8)
            opened = cv2.morphologyEx(blurred, cv2.MORPH_OPEN, kernel)
            height, width = opened.shape[:2]
            left = width // 8
            right = width * 7 // 8
            gray = cv2.cvtColor(opened[:, left:right], cv2.COLOR_BGR2GRAY)
            hsv = cv2.cvtColor(opened[:, left:right], cv2.COLOR_BGR2HSV)
            edges = cv2.Canny(gray, 50, 150, apertureSize=3)
            contours, _ = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
            largest_contour = None
            max_area = 0
            for contour in contours:
                area = cv2.contourArea(contour)
                if area > max_area:
                    max_area = area
                    largest_contour = contour

            if largest_contour is not None:
                x, y, w, h = cv2.boundingRect(largest_contour)
                if w * h > 40000:
                    self.find_rect = 1
                    x += left
                    cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
                    rect = cv2.minAreaRect(largest_contour)
                    box = cv2.boxPoints(rect)
                    box = np.intp(box)
                    box[:, 0] += left
                    self.angle = rect[2]
                    self.jiaodu = self.angle * 180 / np.pi
                    sorted_box = sorted(box, key=lambda p: (p[1], p[0]))
                    top_left = min(sorted_box, key=lambda p: p[0] + p[1])
                    bottom_right = max(sorted_box, key=lambda p: p[0] + p[1])
                    top_right = min(sorted_box, key=lambda p: p[0] - p[1])
                    bottom_left = max(sorted_box, key=lambda p: p[0] - p[1])
                    self.top_left = tuple(sorted_box[0])
                    self.top_right = tuple(sorted_box[1])
                    self.bottom_right = tuple(sorted_box[2])
                    self.bottom_left = tuple(sorted_box[3])
                    self.royal_rect_points = np.array(
                        [self.top_left, self.top_right, self.bottom_right, self.bottom_left], dtype=np.int32)
                    self.royal_rect_points = self.royal_rect_points.reshape((-1, 1, 2))
                    cv2.drawContours(frame, [box], 0, (0, 255, 0), 2)
                    self.xiao_xiebian_half = np.linalg.norm(self.center_big_square - top_left) / 3
                    self.bianchang_half = np.linalg.norm(top_right - top_left) / 6
                    self.square_size = self.bianchang_half * 2
                    self.neijie_radius = self.square_size // 2
                    self.center_big_square = np.array(
                        [(self.top_left[0] + self.bottom_right[0]) / 2, (self.top_left[1] + self.bottom_right[1]) / 2],
                        dtype=np.float64)
                    self.width = max(self.distance_fl64(top_left, top_right),
                                     self.distance_fl64(bottom_left, bottom_right))
                    self.height = max(self.distance_fl64(top_left, bottom_left),
                                      self.distance_fl64(top_right, bottom_right))
                    rotation_matrix = np.array([[np.cos(self.angle), -np.sin(self.angle)],
                                                [np.sin(self.angle), np.cos(self.angle)]])
                    square_order = [(0, 0), (0, 1), (0, 2),
                                    (1, 0), (1, 1), (1, 2),
                                    (2, 0), (2, 1), (2, 2)]
                    self.squares_center.clear()
                    self.square_points.clear()
                    for row, col in square_order:
                        relative_center = np.array([(2 * col - 2) * self.width / 6, (2 * row - 2) * self.height / 6])
                        rotated_center = np.dot(rotation_matrix, relative_center)
                        absolute_center = self.center_big_square + rotated_center
                        self.squares_center.append((absolute_center, row * 3 + col + 1))
                    if self.angle < 0:
                        self.squares_center[1], self.squares_center[3] = self.squares_center[3], self.squares_center[1]
                        self.squares_center[2], self.squares_center[6] = self.squares_center[6], self.squares_center[2]
                        self.squares_center[5], self.squares_center[7] = self.squares_center[7], self.squares_center[5]
                    self.square_points = []
                    for center, number in self.squares_center:
                        relative_points = np.array([(-self.bianchang_half, -self.bianchang_half),
                                                    (self.bianchang_half, -self.bianchang_half),
                                                    (self.bianchang_half, self.bianchang_half),
                                                    (-self.bianchang_half, self.bianchang_half)])
                        rotated_points = np.dot(rotation_matrix, relative_points.T).T
                        absolute_points = rotated_points + center
                        self.square_points.append(absolute_points.astype(int))
                    self.average_colors = []
                    for center, number in self.squares_center:
                        mask = np.zeros((height, width), np.uint8)
                        center_int = tuple(center.astype(int))
                        radius_int = int(self.neijie_radius)
                        cv2.circle(mask, center_int, radius_int, 1, thickness=-1)
                        average_color = cv2.mean(frame, mask=mask)[:3]
                        self.average_colors.append(average_color)
                        text = str(int(average_color[1]))
                        cv2.putText(frame, text, center_int, cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)

                original_circles = cv2.HoughCircles(edges, cv2.HOUGH_GRADIENT, dp=1, minDist=20,
                                                    param1=50, param2=20, minRadius=20, maxRadius=50)
                count_yuan_in = 0
                count_yuan_in_Black = 0
                count_yuan_in_White = 0
                count_yuan_out = 0
                count_yuan_out_Black = 0
                count_yuan_out_White = 0

                if original_circles is not None and self.find_rect == 1:
                    circles = []
                    threshold = self.xiao_xiebian_half
                    for i in original_circles[0, :]:
                        center = (i[0] + left, i[1])
                        radius = i[2]
                        if np.pi * (radius ** 2) < 5000:
                            circles.append(i)
                    for i in circles:
                        center = (i[0] + left, i[1])
                        radius = i[2]
                        white_mask = cv2.inRange(frame, self.white_lower, self.white_upper)
                        black_mask = cv2.inRange(frame, self.black_lower, self.black_upper)
                        if 0 <= center[1] < frame.shape[0] and 0 <= center[0] < frame.shape[1]:
                            color = frame[center[1], center[0]]
                        else:
                            continue
                        pt = (float(center[0]), float(center[1]))
                        yuan_point_position = cv2.pointPolygonTest(self.royal_rect_points, pt, False)

                        if yuan_point_position > 0:
                            if white_mask[center[1], center[0]] > 0:
                                count_yuan_in_White += 1
                            elif black_mask[center[1], center[0]] > 0:
                                count_yuan_in_Black += 1
                            count_yuan_in += 1
                        else:
                            if white_mask[center[1], center[0]] > 0:
                                count_yuan_out_White += 1
                            elif black_mask[center[1], center[0]] > 0:
                                count_yuan_out_Black += 1
                            count_yuan_out += 1

                        circumference = 2 * np.pi * radius
                        if circumference <= 0:
                            continue
                        if self.white_mask is not None and self.black_mask is not None:
                            white_pixels = cv2.countNonZero(self.white_mask)
                            black_pixels = cv2.countNonZero(self.black_mask)
                            if white_pixels > black_pixels:
                                white_count = white_pixels
                                black_count = black_pixels
                            else:
                                white_count = black_pixels
                                black_count = white_pixels
                        else:
                            continue

                        self.white_window.pop(0)
                        self.white_window.append(white_count)
                        self.black_window.pop(0)
                        self.black_window.append(black_count)
                        white_count_avg = round(sum(self.white_window) / len(self.white_window))
                        black_count_avg = round(sum(self.black_window) / len(self.black_window))
                        self.text_label_5.setText(f"当前剩余{count_yuan_out_Black}颗黑棋 {count_yuan_out_White}颗白棋")

                        for p, average_color in enumerate(self.average_colors):
                            if average_color[0] > WHITE_THRESHOLD and average_color[1] > WHITE_THRESHOLD:
                                self.jiugongge[p] = 2
                            elif average_color[1] < BLACK_THRESHOLD and average_color[2] < BLACK_THRESHOLD:
                                self.jiugongge[p] = 1
                            else:
                                self.jiugongge[p] = 0
                        if self.time_loop >= 3:
                            self.paint_chess()
                            self.winner = self.check_win(self.jiugongge)
                            self.move = self.find_best_move(self.jiugongge)
                            if self.winner == -1:
                                self.text_label_2.setText(f"Ai决定下第{self.move + 1}位")
                            elif (self.zhixing == 1 and self.winner == 1) or (self.zhixing == 2 and self.winner == 2):
                                self.text_label_1.setText("胜利者:Ai")
                            elif (self.zhixing == 1 and self.winner == 2) or (self.zhixing == 2 and self.winner == 1):
                                self.text_label_3.setText(" ")
                            elif self.winner == 0:
                                self.text_label_3.setText(" ")
                            self.time_loop = 0

            image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            height, width, _ = image.shape
            bytesPerLine = 3 * width
            qImg = QImage(image.data, width, height, bytesPerLine, QImage.Format_RGB888)
            pixmap = QPixmap.fromImage(qImg)
            self.video_label.setPixmap(pixmap.scaled(*self.video_size))
            self.image_11_label.setPixmap(pixmap.scaled(400, 400, Qt.KeepAspectRatio))

    def distance_fl64(self, point1, point2):
        point1 = np.array(point1, dtype=np.float64)
        point2 = np.array(point2, dtype=np.float64)
        return ((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2) ** 0.5

    def check_win(self, jiugongge):
        win_conditions = [
            (0, 1, 2), (3, 4, 5), (6, 7, 8),
            (0, 3, 6), (1, 4, 7), (2, 5, 8),
            (0, 4, 8), (2, 4, 6)
        ]
        for a, b, c in win_conditions:
            if jiugongge[a] == jiugongge[b] == jiugongge[c] != 0:
                return jiugongge[a]
        if 0 not in jiugongge:
            return 0
        return -1

    def evaluate(self, jiugongge):
        winner = self.check_win(jiugongge)
        if winner == self.zhixing:
            return 10
        elif winner == 3 - self.zhixing:
            return -10
        score = 0
        for (a, b, c) in [(0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)]:
            line = [jiugongge[a], jiugongge[b], jiugongge[c]]
            if line.count(self.zhixing) == 2 and line.count(0) == 1:
                score += 5
            if line.count(3 - self.zhixing) == 2 and line.count(0) == 1:
                score -= 4
        return score

    def minimax(self, jiugongge, depth, alpha, beta, is_maximizing):
        score = self.evaluate(jiugongge)
        if score == 10 or score == -10:
            return score
        if 0 not in jiugongge:
            return 0
        if is_maximizing:
            best = -float('inf')
            for i in range(9):
                if jiugongge[i] == 0:
                    jiugongge[i] = self.zhixing
                    best = max(best, self.minimax(jiugongge, depth + 1, alpha, beta, False))
                    jiugongge[i] = 0
                    alpha = max(alpha, best)
                    if beta <= alpha:
                        break
            return best
        else:
            best = float('inf')
            for i in range(9):
                if jiugongge[i] == 0:
                    jiugongge[i] = 3 - self.zhixing
                    best = min(best, self.minimax(jiugongge, depth + 1, alpha, beta, True))
                    jiugongge[i] = 0
                    beta = min(beta, best)
                    if beta <= alpha:
                        break
            return best

    def find_best_move(self, jiugongge):
        best_val = -float('inf')
        self.move = -1
        for i in range(9):
            if jiugongge[i] == 0:
                jiugongge[i] = self.zhixing
                move_val = self.minimax(jiugongge, 0, -float('inf'), float('inf'), False)
                jiugongge[i] = 0
                if move_val > best_val or (move_val == best_val and i == 4):
                    self.move = i
                    best_val = move_val
        return self.move

    def paint_chess(self):
        pixmap = self.image_label.pixmap().copy()
        painter = QPainter(pixmap)
        for i in range(9):
            pt2 = self.weizhi[i]
            if self.jiugongge[i] == 0:
                pen = QPen(QColor(255, 255, 255), 10)
                brush = QBrush(QColor(255, 255, 255))
            elif self.jiugongge[i] == 1:
                pen = QPen(QColor(0, 0, 0), 10)
                brush = QBrush(QColor(0, 0, 0))
            elif self.jiugongge[i] == 2:
                pen = QPen(QColor(192, 192, 192), 10)
                brush = QBrush(QColor(192, 192, 192))
            painter.setPen(pen)
            painter.setBrush(brush)
            painter.drawEllipse(pt2[0], pt2[1], 60, 60)
        painter.end()
        self.image_label.setPixmap(pixmap)

    def switch_button_clicked(self, event):
        self.zhixing = 1 if self.zhixing == 2 else 2
        self.no_1 = 1 if self.zhixing == 1 else 2
        self.text_label.setText("系统执黑棋" if self.zhixing == 1 else "系统执白棋")

    def switch_button_1_clicked(self, event):
        self.people_move = 1
        self.system_move = 0
        if self.zhixing == 1:
            if self.temp_jiugongge != [1 if i == 1 else 0 for i in self.jiugongge]:
                self.text_label_cheat_state.setText("有作弊")
                self.cheat_flag = 1
            else:
                self.text_label_cheat_state.setText("无作弊")
                self.cheat_flag = 0
        else:
            if self.temp_jiugongge != [1 if i == 2 else 0 for i in self.jiugongge]:
                self.text_label_cheat_state.setText("有作弊")
            else:
                self.text_label_cheat_state.setText("无作弊")

    def square_button_simulation_clicked(self, event):
        self.system_move = 1
        self.people_move = 0
        if self.zhixing == 1:
            self.temp_jiugongge = [1 if i == 1 else 0 for i in self.jiugongge]
        else:
            self.temp_jiugongge = [1 if i == 2 else 0 for i in self.jiugongge]

    def square_button_0_clicked(self, event):
        self.test_jiugongge[0] = (self.test_jiugongge[0] + 1) % 3
        self.square_button_0.setText(
            "黑" if self.test_jiugongge[0] == 1 else ("白" if self.test_jiugongge[0] == 2 else "空"))

    def square_button_1_clicked(self, event):
        self.test_jiugongge[1] = (self.test_jiugongge[1] + 1) % 3
        self.square_button_1.setText(
            "黑" if self.test_jiugongge[1] == 1 else ("白" if self.test_jiugongge[1] == 2 else "空"))

    def square_button_2_clicked(self, event):
        self.test_jiugongge[2] = (self.test_jiugongge[2] + 1) % 3
        self.square_button_2.setText(
            "黑" if self.test_jiugongge[2] == 1 else ("白" if self.test_jiugongge[2] == 2 else "空"))

    def square_button_3_clicked(self, event):
        self.test_jiugongge[3] = (self.test_jiugongge[3] + 1) % 3
        self.square_button_3.setText(
            "黑" if self.test_jiugongge[3] == 1 else ("白" if self.test_jiugongge[3] == 2 else "空"))

    def square_button_4_clicked(self, event):
        self.test_jiugongge[4] = (self.test_jiugongge[4] + 1) % 3
        self.square_button_4.setText(
            "黑" if self.test_jiugongge[4] == 1 else ("白" if self.test_jiugongge[4] == 2 else "空"))

    def square_button_5_clicked(self, event):
        self.test_jiugongge[5] = (self.test_jiugongge[5] + 1) % 3
        self.square_button_5.setText(
            "黑" if self.test_jiugongge[5] == 1 else ("白" if self.test_jiugongge[5] == 2 else "空"))

    def square_button_6_clicked(self, event):
        self.test_jiugongge[6] = (self.test_jiugongge[6] + 1) % 3
        self.square_button_6.setText(
            "黑" if self.test_jiugongge[6] == 1 else ("白" if self.test_jiugongge[6] == 2 else "空"))

    def square_button_7_clicked(self, event):
        self.test_jiugongge[7] = (self.test_jiugongge[7] + 1) % 3
        self.square_button_7.setText(
            "黑" if self.test_jiugongge[7] == 1 else ("白" if self.test_jiugongge[7] == 2 else "空"))

    def square_button_8_clicked(self, event):
        self.test_jiugongge[8] = (self.test_jiugongge[8] + 1) % 3
        self.square_button_8.setText(
            "黑" if self.test_jiugongge[8] == 1 else ("白" if self.test_jiugongge[8] == 2 else "空"))


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = VideoWindow()
    window.show()
    sys.exit(app.exec_())